package qc.module.platform.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.common.core.exception.QCPromptException;
import qc.module.platform.dto.config.group.ConfigGroupDto;
import qc.module.platform.dto.config.group.ConfigGroupQueryConditionDto;
import qc.module.platform.dto.project.ProjectDto;
import qc.module.platform.entity.QcProjectConfigGroups;
import qc.module.platform.mapper.ProjectConfigGroupsMapper;
import qc.module.platform.repository.QcProjectConfigGroupsRepository;

import java.util.List;

/**
 * ProjectConfigGroupsService
 *
 * @author QuCheng Tech
 * @create 2023/02/07
 */
@Service
public class ProjectConfigGroupsService {
    private QcProjectConfigGroupsRepository repository;

    @Autowired
    public void setQcProjectConfigGroupsRepository(QcProjectConfigGroupsRepository repository) {
        this.repository = repository;
    }

    private ProjectService projectService;

    @Autowired
    public void setProjectService(ProjectService projectService) {
        this.projectService = projectService;
    }

    /**
     * 根据条件查询分组信息
     *
     * @param dto ConfigGroupQueryConditionDto
     * @return 分组信息集合
     * @author QcCheng Tech
     * @since 2023/2/8
     */
    public List<ConfigGroupDto> getAllByGroupCodeAndProjectCode(ConfigGroupQueryConditionDto dto) throws Exception {
        if (dto == null)
            throw new QCPromptException("传入对象为空");
        if (StringUtils.isBlank(dto.getPcode()))
            throw new QCPromptException("项目编码不能为空");
        if (StringUtils.isBlank(dto.getGcode()))
            throw new QCPromptException("分组编码不能为空");

        //验证指定项目编码以及项目启用状态
        ProjectDto project = projectService.get(dto.getPcode());
        if (project == null)
            throw new QCPromptException("项目不存在");
        if (!project.getFlag().equals(ResourceStatusFlagEnum.NORMAL))
            throw new QCPromptException("项目未启用");


        LambdaQueryWrapper<QcProjectConfigGroups> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(QcProjectConfigGroups::getCode, dto.getGcode()).eq(QcProjectConfigGroups::getProjectcode, dto.getPcode());
        wrapper.orderByDesc(QcProjectConfigGroups::getCode);

        List<QcProjectConfigGroups> groupsList = repository.selectList(wrapper);

        if (groupsList.size() > 0x0)
            return ProjectConfigGroupsMapper.MAPPER.toDtoList(groupsList);

        return null;
    }
}
